//
//  ProductCell.m
//  iFlower
//
//  Created by thohd on 7/30/10.
//  Copyright 2010 iNIL.me. All rights reserved.
//

#import "ProductCell.h"


@implementation ProductCell

@synthesize photo;
@synthesize item;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
        
        scrollingWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(27.0, 27.0, 20.0, 20.0)];
        scrollingWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        scrollingWheel.hidesWhenStopped = YES;
        [scrollingWheel stopAnimating];
        [self.contentView addSubview:scrollingWheel];
        
        self.accessoryType = UITableViewCellAccessoryNone;
    }
    return self;
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
#pragma mark -
#pragma mark Public methods

- (void)setItem:(Product *)newItem
{
    if (newItem != item)
    {
        item.delegate = nil;
        [item release];
        item = nil;
        
        item = [newItem retain];
        [item setDelegate:self];
        
        if (item!=nil)
        {
            
            // This is to avoid the item loading the image
            // when this setter is called; we only want that
            // to happen depending on the scrolling of the table
            if ([item hasLoadedThumbnail])
            {
                photo.image = item.thumbnail;
            }
            else
            {
                photo.image = nil;
            }
        }
    }
}
- (void)loadImage
{
    // The getter in the FlickrItem class is overloaded...!
    // If the image is not yet downloaded, it returns nil and 
    // begins the asynchronous downloading of the image.
    UIImage *image = item.thumbnail;
    if (image == nil)
    {
        [scrollingWheel startAnimating];
    }
    photo.image = image;
}
#pragma mark -
#pragma mark ProductDelegate methods

- (void)product:(Product *)item didLoadThumbnail:(UIImage *)image
{
    photo.image = image;
    [scrollingWheel stopAnimating];
}

- (void)product:(Product *)item couldNotLoadImageError:(NSError *)error
{
    // Here we could show a "default" or "placeholder" image...
    [scrollingWheel stopAnimating];
}




- (void)dealloc {
	[scrollingWheel release];
    [item setDelegate:nil];
    [item release];
	[photo release];
    [super dealloc];
}
@end
